package com.ruoyi.web.controller.glzz;

import com.alibaba.fastjson2.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.dao.MqttDao;
import com.ruoyi.web.dev.OnMessageCallback;
import com.ruoyi.web.domain.glzz.TGlzzMenu;
import com.ruoyi.web.domain.glzz.dao.TGlzzMenuAddDao;
import com.ruoyi.web.domain.glzz.dao.TGlzzMenuUpdateDao;
import com.ruoyi.web.domain.glzz.excel.TGlzzMenuExcelDao;
import com.ruoyi.web.service.glzz.ITGlzzMenuService;
import com.ruoyi.web.utils.RevertEntityUtil;
import io.swagger.annotations.*;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * glzz菜单Controller
 *
 * @author sci
 * @date 2024-05-13
 */
@SuppressWarnings({"DefaultAnnotationParam", "PointlessBooleanExpression"})
@Api(value = "glzz菜单", tags = {"glzz菜单API"})
@RestController
@RequestMapping("/system/glzzMenu")

@Slf4j
public class TGlzzMenuController extends BaseController {
    @Autowired
    private ITGlzzMenuService tGlzzMenuService;

    /**
     * 查询glzz菜单列表
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "第几页，从1开始", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "查询出多少条数据", required = false, paramType = "query"),
            @ApiImplicitParam(name = "nodeId", value = "菜单id", required = false, paramType = "query"),
            @ApiImplicitParam(name = "parentNodeId", value = "菜单父id", required = false, paramType = "query"),
            @ApiImplicitParam(name = "metaTitle", value = "菜单名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "app", value = "是否显示", required = false, paramType = "query"),
            @ApiImplicitParam(name = "web", value = "是否显示", required = false, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "是否启用", required = false, paramType = "query"),
            @ApiImplicitParam(name = "moduleIcon", value = "模块图标", required = false, paramType = "query"),
            @ApiImplicitParam(name = "name", value = "路由名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "component", value = "组件名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "metaIcon", value = "显示图标", required = false, paramType = "query"),
            @ApiImplicitParam(name = "metaIconActive", value = "激活图标", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "路由地址", required = false, paramType = "query"),
            @ApiImplicitParam(name = "freeUse", value = "免费使用", required = false, paramType = "query"),
            @ApiImplicitParam(name = "keepAlive", value = "前端缓存", required = false, paramType = "query"),
            @ApiImplicitParam(name = "remarks", value = "备注介绍", required = false, paramType = "query")
    })
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('system:glzzMenu:list')")
    @GetMapping("/list")
    public AjaxResult list(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "nodeId", required = false) String nodeId,
            @RequestParam(value = "parentNodeId", required = false) String parentNodeId,
            @RequestParam(value = "metaTitle", required = false) String metaTitle,
            @RequestParam(value = "app", required = false) Integer app,
            @RequestParam(value = "web", required = false) Integer web,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "moduleIcon", required = false) String moduleIcon,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "component", required = false) String component,
            @RequestParam(value = "metaIcon", required = false) String metaIcon,
            @RequestParam(value = "metaIconActive", required = false) String metaIconActive,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "freeUse", required = false) Long freeUse,
            @RequestParam(value = "keepAlive", required = false) Long keepAlive,
            @RequestParam(value = "remarks", required = false) String remarks
    ) {
        LambdaQueryWrapper<TGlzzMenu> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Objects.nonNull(id), TGlzzMenu::getId, id);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(nodeId), TGlzzMenu::getNodeId, nodeId);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(parentNodeId), TGlzzMenu::getParentNodeId, parentNodeId);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(metaTitle), TGlzzMenu::getMetaTitle, metaTitle);
        lambdaQueryWrapper.eq(Objects.nonNull(app), TGlzzMenu::getApp, app);
        lambdaQueryWrapper.eq(Objects.nonNull(web), TGlzzMenu::getWeb, web);
        lambdaQueryWrapper.eq(Objects.nonNull(status), TGlzzMenu::getStatus, status);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(moduleIcon), TGlzzMenu::getModuleIcon, moduleIcon);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name), TGlzzMenu::getName, name);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(component), TGlzzMenu::getComponent, component);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(metaIcon), TGlzzMenu::getMetaIcon, metaIcon);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(metaIconActive), TGlzzMenu::getMetaIconActive, metaIconActive);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(address), TGlzzMenu::getAddress, address);
        lambdaQueryWrapper.eq(Objects.nonNull(freeUse), TGlzzMenu::getFreeUse, freeUse);
        lambdaQueryWrapper.eq(Objects.nonNull(keepAlive), TGlzzMenu::getKeepAlive, keepAlive);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(remarks), TGlzzMenu::getRemarks, remarks);
        lambdaQueryWrapper.orderByAsc(TGlzzMenu::getOrderNum);
        List<TGlzzMenu> list = tGlzzMenuService.list(lambdaQueryWrapper);
////      读取目标文件夹下文件并全部转为应为
//        try {
//            String s = sendGetRequest("https://api.kertennet.com/geography/locationInfo?lat=31.14581&lng=121.67892");
//        } catch (IOException e) {
////
////
//        }
        return success(list);
    }

    public static String sendGetRequest(String url) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为GET
        con.setRequestMethod("GET");

        // 发送请求并获取响应码
        int responseCode = con.getResponseCode();

        // 输出响应码
        System.out.println("Response Code : " + responseCode);

        // 如果响应码是200，表示请求成功
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 从输入流中读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 返回响应数据
            return response.toString();
        } else {
            // 请求失败，返回错误消息
            return "GET request not worked";
        }
    }


    private static final String API_URL = "https://restapi.amap.com/v3/geocode/regeo";
    private static final String KEY = "1f123e41bb19507fc9554bb57a0e8630";

    public static String getProvinceCityDistrict(double longitude, double latitude) {
        String parameters = "?key=" + KEY;
        parameters += "&location=" + longitude + "," + latitude;
        parameters += "&extensions=all";
        parameters += "&output=JSON";

        String urlString = API_URL + parameters;
        StringBuilder res = new StringBuilder();

        try {
            log.info("Amap API Request URL: " + urlString);
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line);
            }
            in.close();

            log.info("Map API Response: " + res);

            JSONObject json = JSONObject.parseObject(res.toString());
            if ("1".equals(json.getString("status"))) {
                JSONObject regeocode = json.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");

                return "City:" + city + ", District:" + district;
            } else {
                log.info("Map API Response Error: " + json.getString("info"));
            }
        } catch (Exception e) {
            log.info("Error getting address information");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 导出glzz菜单列表
     */
    @ApiOperation("导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nodeId", value = "菜单id", required = false, paramType = "query"),
            @ApiImplicitParam(name = "parentNodeId", value = "菜单父id", required = false, paramType = "query"),
            @ApiImplicitParam(name = "metaTitle", value = "菜单名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "app", value = "是否显示", required = false, paramType = "query"),
            @ApiImplicitParam(name = "web", value = "是否显示", required = false, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "是否启用", required = false, paramType = "query"),
            @ApiImplicitParam(name = "moduleIcon", value = "模块图标", required = false, paramType = "query"),
            @ApiImplicitParam(name = "name", value = "路由名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "component", value = "组件名", required = false, paramType = "query"),
            @ApiImplicitParam(name = "metaIcon", value = "显示图标", required = false, paramType = "query"),
            @ApiImplicitParam(name = "metaIconActive", value = "激活图标", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "路由地址", required = false, paramType = "query"),
            @ApiImplicitParam(name = "freeUse", value = "免费使用", required = false, paramType = "query"),
            @ApiImplicitParam(name = "keepAlive", value = "前端缓存", required = false, paramType = "query"),
            @ApiImplicitParam(name = "remarks", value = "备注介绍", required = false, paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('system:glzzMenu:export')")
    @Log(title = "glzz菜单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(value = "nodeId", required = false) String nodeId,
                       @RequestParam(value = "parentNodeId", required = false) String parentNodeId,
                       @RequestParam(value = "metaTitle", required = false) String metaTitle,
                       @RequestParam(value = "app", required = false) Integer app,
                       @RequestParam(value = "web", required = false) Integer web,
                       @RequestParam(value = "status", required = false) Integer status,
                       @RequestParam(value = "moduleIcon", required = false) String moduleIcon,
                       @RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "component", required = false) String component,
                       @RequestParam(value = "metaIcon", required = false) String metaIcon,
                       @RequestParam(value = "metaIconActive", required = false) String metaIconActive,
                       @RequestParam(value = "address", required = false) String address,
                       @RequestParam(value = "freeUse", required = false) Long freeUse,
                       @RequestParam(value = "keepAlive", required = false) Long keepAlive,
                       @RequestParam(value = "remarks", required = false) String remarks
    ) {
        LambdaQueryWrapper<TGlzzMenu> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(nodeId), TGlzzMenu::getNodeId, nodeId);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(parentNodeId), TGlzzMenu::getParentNodeId, parentNodeId);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(metaTitle), TGlzzMenu::getMetaTitle, metaTitle);
        lambdaQueryWrapper.eq(Objects.nonNull(app), TGlzzMenu::getApp, app);
        lambdaQueryWrapper.eq(Objects.nonNull(web), TGlzzMenu::getWeb, web);
        lambdaQueryWrapper.eq(Objects.nonNull(status), TGlzzMenu::getStatus, status);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(moduleIcon), TGlzzMenu::getModuleIcon, moduleIcon);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name), TGlzzMenu::getName, name);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(component), TGlzzMenu::getComponent, component);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(metaIcon), TGlzzMenu::getMetaIcon, metaIcon);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(metaIconActive), TGlzzMenu::getMetaIconActive, metaIconActive);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(address), TGlzzMenu::getAddress, address);
        lambdaQueryWrapper.eq(Objects.nonNull(freeUse), TGlzzMenu::getFreeUse, freeUse);
        lambdaQueryWrapper.eq(Objects.nonNull(keepAlive), TGlzzMenu::getKeepAlive, keepAlive);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(remarks), TGlzzMenu::getRemarks, remarks);
        List<TGlzzMenu> list = tGlzzMenuService.list(lambdaQueryWrapper);
        ExcelUtil<TGlzzMenuExcelDao> util = new ExcelUtil<TGlzzMenuExcelDao>(TGlzzMenuExcelDao.class);
        List<TGlzzMenuExcelDao> tGlzzMenuExcelDaos = RevertEntityUtil.convertList(list, TGlzzMenuExcelDao.class);
        util.exportExcel(response, tGlzzMenuExcelDaos, "glzz菜单数据");
    }

    /**
     * 获取glzz菜单详细信息
     */
    @ApiOperation("详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, paramType = "query"),
    })
    @PreAuthorize("@ss.hasPermi('system:glzzMenu:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        LambdaQueryWrapper<TGlzzMenu> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(TGlzzMenu::getId, id);
        TGlzzMenu tGlzzMenu = tGlzzMenuService.getOne(lambdaQueryWrapper);
        if (Objects.isNull(tGlzzMenu)) {
            return AjaxResult.error("未查询到数据");
        }
        return success(tGlzzMenu);
    }

    /**
     * 新增glzz菜单
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('system:glzzMenu:add')")
    @Log(title = "glzz菜单", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody TGlzzMenuAddDao tGlzzMenuAddDao
    ) {

//        String name = tGlzzMenuAddDao.getName();
//        List<TGlzzMenu> list4 = tGlzzMenuService.lambdaQuery().eq(TGlzzMenu::getName,name).list();
//        if(list4.size()>0){
//            return error("路由名称重复");
//        }

        if (Objects.isNull(tGlzzMenuAddDao.getNodeId())) {
            return error("菜单id必填");
        }
        LambdaQueryWrapper<TGlzzMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TGlzzMenu::getNodeId, tGlzzMenuAddDao.getNodeId());
        List<TGlzzMenu> list = tGlzzMenuService.list(lambdaQueryWrapper);
        if (list.size() > 0) {
            return error("菜单id重复");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getParentNodeId())) {
            return error("菜单父id必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getMetaTitle())) {
            return error("菜单必填必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getMetaTitleAlias())) {
            return error("菜单别名必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getOrderNum())) {
            return error("菜单顺序必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getStatus())) {
            return error("是否启用必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getName())) {
            return error("路由名必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getComponent())) {
            return error("组件名必填");
        }
        if (Objects.isNull(tGlzzMenuAddDao.getAddress())) {
            return error("路由地址必填");
        }

        TGlzzMenu tGlzzMenu = new TGlzzMenu();
        // region 插入数据-参数填充
        tGlzzMenu.setNodeId(tGlzzMenuAddDao.getNodeId());
        tGlzzMenu.setParentNodeId(tGlzzMenuAddDao.getParentNodeId());
        tGlzzMenu.setMetaTitle(tGlzzMenuAddDao.getMetaTitle());
        tGlzzMenu.setMetaTitleAlias(tGlzzMenuAddDao.getMetaTitleAlias());
        tGlzzMenu.setApp(tGlzzMenuAddDao.getApp());
        tGlzzMenu.setWeb(tGlzzMenuAddDao.getWeb());
        tGlzzMenu.setStatus(tGlzzMenuAddDao.getStatus());
        tGlzzMenu.setModuleIcon(tGlzzMenuAddDao.getModuleIcon());
        tGlzzMenu.setName(tGlzzMenuAddDao.getName());
        tGlzzMenu.setComponent(tGlzzMenuAddDao.getComponent());
        tGlzzMenu.setMetaIcon(tGlzzMenuAddDao.getMetaIcon());
        tGlzzMenu.setMetaIconActive(tGlzzMenuAddDao.getMetaIconActive());
        tGlzzMenu.setAddress(tGlzzMenuAddDao.getAddress());
        tGlzzMenu.setFreeUse(tGlzzMenuAddDao.getFreeUse());
        tGlzzMenu.setKeepAlive(tGlzzMenuAddDao.getKeepAlive());
        tGlzzMenu.setRemarks(tGlzzMenuAddDao.getRemarks());
        tGlzzMenu.setOrderNum(tGlzzMenuAddDao.getOrderNum());
        tGlzzMenu.setIsDev(tGlzzMenuAddDao.getIsDev());
        tGlzzMenu.setShowUrl(tGlzzMenuAddDao.getShowUrl());
        tGlzzMenu.setAppNodeCode(tGlzzMenuAddDao.getAppNodeCode());
        tGlzzMenu.setAppOrderNum(tGlzzMenuAddDao.getAppOrderNum());
//      完善层级
        if (!tGlzzMenuAddDao.getParentNodeId().equals("0")) {
            TGlzzMenu one = tGlzzMenuService.lambdaQuery().eq(TGlzzMenu::getNodeId, tGlzzMenuAddDao.getParentNodeId()).one();
            if (Objects.nonNull(one)) {
                Integer level = one.getLevel();
                tGlzzMenu.setLevel(level + 1);
            }
        } else {
            tGlzzMenu.setLevel(0);
        }
        boolean success = tGlzzMenuService.save(tGlzzMenu);
        if (success == false) {
            return toAjax(false);
        }
        return toAjax(true);
    }

    /**
     * 修改glzz菜单
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('system:glzzMenu:edit')")
    @Log(title = "glzz菜单", businessType = BusinessType.UPDATE)
    @PostMapping("update")
    public AjaxResult update(@RequestBody TGlzzMenuUpdateDao tGlzzMenuUpdateDao
    ) {

        return tGlzzMenuService.updateTrans(tGlzzMenuUpdateDao);
    }

    @Autowired
    RestTemplate restTemplate;

//    /**
//     * shuaixnqiyebianam
//     */
//    @ApiOperation("设置")
//    @PreAuthorize("@ss.hasPermi('system:glzzMenu:edit')")
//    @Log(title = "glzz菜单", businessType = BusinessType.UPDATE)
//    @PostMapping("handleSetGlzzMenu")
//    public AjaxResult handleSetGlzzMenu(@RequestBody TGlzzMenuSetDao tGlzzMenuSetDao
//    ) {
//        String code = tGlzzMenuSetDao.getCode();
//        List<Integer> idList = tGlzzMenuSetDao.getIdList();
//
//        // 根据响应状态码判断请求是否成功
//        boolean success = true;
//        if (success == false) {
//            return toAjax(false);
//        }
//        return toAjax(true);
//    }

    /**
     * 删除glzz菜单
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('system:glzzMenu:remove')")
    @Log(title = "glzz菜单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
//      在完善t todo
        List<TGlzzMenu> list = tGlzzMenuService.listByIds(Arrays.asList(ids));
        for (TGlzzMenu tGlzzMenu : list) {
            String nodeId = tGlzzMenu.getNodeId();
            List<TGlzzMenu> list1 = tGlzzMenuService.lambdaQuery().eq(TGlzzMenu::getParentNodeId, nodeId).list();
            if (list1.size() > 0) {
//               如果有上级那就不鞥能删除
                return AjaxResult.error("删除失败，有上级");
            }
        }
        if (list.isEmpty()) {
            return AjaxResult.error("删除失败，未查询到数据");
        }
        boolean success = tGlzzMenuService.removeBatchByIds(list);
        if (success == false) {
            return toAjax(false);
        }
        return toAjax(true);
    }

    @ApiOperation("复制")
    @GetMapping("/copy/{id}")
    public AjaxResult copy(@PathVariable String id) {
        TGlzzMenu byId = tGlzzMenuService.getById(id);
        byId.setId(null);
        byId.setNodeId(byId.getNodeId() + "复制");
        boolean save = tGlzzMenuService.save(byId);
        return success(save);
    }

    @ApiOperation("发送mqtt消息")
    @PostMapping("/sendMqtt")
    public AjaxResult sendMqtt(@RequestBody MqttDao mqttDao) {
        String pubTopic = mqttDao.getPubTopic();
        String content = mqttDao.getSendContent();
//        String content = "{\n" +
//                "    \"deviceId\":\"10001\",\n" +
//                "    \"messageId\":\"abcdeeeee\",\n" +
//                "    \"latitude\":\"35.927624\",\n" +
//                "    \"longitude\":\"120.511454\",\n" +
//                "    \"timestamp\":\"172019100000\" ,\n" +
//                "    \"electricity\": \"0.9\"\n" +
//                "}";
        int qos = mqttDao.getQos();
//      emqx免费服务器
//        String broker = "tcp://broker.emqx.io:1883";
        String broker =mqttDao.getBroker();
        String clientId = mqttDao.getClientId();
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(mqttDao.getUserName());
            connOpts.setPassword(mqttDao.getPassword().toCharArray());
            // 保留会话

            // 设置回调
            client.setCallback(new OnMessageCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("发送成功");
                }
            });

            // 建立连接
            client.connect(connOpts);
            // 消息发布所需参数
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            client.publish(pubTopic, message);

        } catch (MqttException me) {
//          这里有失败原因
            me.printStackTrace();
        }
        return success();
    }
}
